package hu.issue.framework.web.servlet;

import hu.issue.framework.web.controller.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

class ControllerLoader {
	private final String controllerPackage;

	public ControllerLoader(final String controllerPackage) {
		this.controllerPackage = controllerPackage;
	}

	public Map<String, Controller> loadControllers() throws Exception {
		final Map<String, Controller> controllers = new HashMap<String, Controller>();
		final PackageLoader packageLoader = new PackageLoader(this.controllerPackage);
		final BeanInjector injector = new BeanInjector();
		final List<Class<?>> controllerClasses = packageLoader.loadClasses();
		for (final Class<?> controllerClass : controllerClasses) {
			final String controllerName = getControllerName(controllerClass.getSimpleName());
			final Controller controller = (Controller) controllerClass.newInstance();
			injector.inject(controller);
			controllers.put(controllerName, controller);
		}
		return controllers;
	}

	private String getControllerName(final String simpleClassName) {
		return simpleClassName.replaceAll("Controller", "").toLowerCase();
	}

}
